<template>
  <div class="brand-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="品牌名称">
          <el-input v-model="searchForm.name" placeholder="请输入品牌名称" clearable />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
            <el-option label="通用" value="通用" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 品牌列表 -->
    <el-card class="brand-list-card">
      <template #header>
        <div class="card-header">
          <span>品牌列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增品牌
          </el-button>
        </div>
      </template>

      <el-table :data="brandList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="品牌ID" width="80" />
        <el-table-column prop="name" label="品牌名称" min-width="150" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上线' : '下线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'danger' : 'success'" 
              link 
              @click="handleToggleStatus(scope.row)">
              <el-icon><Switch /></el-icon>
              {{ scope.row.status === 1 ? '下线' : '上线' }}
            </el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增品牌' : '编辑品牌'"
      width="500px"
      @close="handleDialogClose">
      <el-form ref="brandFormRef" :model="brandForm" :rules="brandRules" label-width="100px">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="brandForm.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="brandForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="通用">通用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="brandForm.remarks" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="brandForm.status">
            <el-radio :label="1">上线</el-radio>
            <el-radio :label="0">下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Edit, Delete, Switch
} from '@element-plus/icons-vue'
import { findAllBrands, deleteBrandById, updateBrand, addBrand } from '@/api/brand'
onMounted(() => {
  FindAllBrands();
})
// 搜索表单
const searchForm = reactive({
  name: '',
  sex: ''
})

// 品牌列表数据
const allBrands = ref([])  // 存储所有品牌数据
const brandList = ref([])  // 存储当前页面显示的品牌数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const brandFormRef = ref()

// 品牌表单
const brandForm = reactive({
  id: '',
  name: '',
  sex: '通用',
  remarks: '',
  status: 1
})

// 表单验证规则
const brandRules = {
  name: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 50, message: '品牌名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

const FindAllBrands = async () => {
  try {
    loading.value = true
    const res = await findAllBrands()
    console.log('获取品牌列表响应:', res)
    if (!res || res.status !== 200) {
      ElMessage.error(res?.message || '获取品牌列表失败')
      return
    }
    
    if (!res.data || !Array.isArray(res.data)) {
      console.log('数据格式错误:', res.data)
      ElMessage.error('数据格式错误')
      return
    }
    
    console.log('原始数据:', res.data)
    
    if (res.data.length === 0) {
      ElMessage.warning('暂无品牌数据')
      allBrands.value = []
      brandList.value = []
      total.value = 0
      return
    }
    
    // 映射后端品牌数据到前端格式
    const mappedData = res.data.map(item => {
      console.log('映射前数据项:', item)
      return {
        id: item.bid || item.id,               // 品牌ID (后端使用bid)
        name: item.bname || item.name,         // 品牌名称 (后端使用bname)
        status: item.bstate !== undefined ? item.bstate : (item.status || 1), // 品牌状态 (后端使用bstate)
        sex: item.bsex || '',                  // 性别 (后端使用bsex)
        remarks: item.bremarks || '',          // 备注 (后端使用bremarks)
        createTime: item.createTime || new Date().toLocaleString() // 创建时间
      }
    })
    
    console.log('映射后数据:', mappedData)
    
    allBrands.value = mappedData
    getBrandList()
    
  } catch (error) {
    console.log('获取品牌列表错误:', error)
    ElMessage.error('获取品牌列表失败')
  } finally {
    loading.value = false
  }
}

// 获取品牌列表（处理搜索和分页）
const getBrandList = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    console.log('getBrandList - allBrands:', allBrands.value)
    console.log('getBrandList - searchForm:', searchForm)
    console.log('getBrandList - currentPage:', currentPage.value, 'pageSize:', pageSize.value)
    
    let result = [...allBrands.value]
    
    // 搜索过滤
    if (searchForm.name) {
      result = result.filter(brand => brand.name.includes(searchForm.name))
    }
    if (searchForm.sex) {
      result = result.filter(brand => brand.sex === searchForm.sex)
    }

    
    console.log('getBrandList - 过滤后数据:', result)
    
    // 保存过滤后的总数
    const filteredTotal = result.length
    
    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    
    console.log('getBrandList - 分页参数 start:', start, 'end:', end)
    
    // 创建分页后的数据副本
    const paginatedData = result.slice(start, end)
    
    console.log('getBrandList - 分页后数据:', paginatedData)
    
    // 更新显示的数据和总数
    brandList.value = paginatedData
    total.value = filteredTotal
    
    console.log('getBrandList - 最终显示数据:', brandList.value, '总数:', total.value)
    
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getBrandList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  searchForm.sex = ''
  handleSearch()
}

// 新增品牌
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑品牌
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(brandForm, {
    id: row.id,
    name: row.name,
    sex: row.sex || '通用',
    picture: row.picture,
    remarks: row.remarks || '',
    status: row.status
  })
  dialogVisible.value = true
}

// 切换品牌状态
const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '下线' : '上线'
  const newStatus = row.status === 1 ? 0 : 1
  
  ElMessageBox.confirm(
    `确定要${action}品牌 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      
      // 更新品牌状态 - 适配后端字段格式
        const updateData = {
          bid: row.id,
          bname: row.name,
          bsex: row.sex || '通用',
          bremarks: row.remarks || '',
          bstate: newStatus
        }
      
      const res = await updateBrand(updateData)
      
      if (res && res.status === 200) {
        row.status = newStatus
        ElMessage.success(`${action}成功`)
      } else {
        ElMessage.error(res?.message || `${action}失败`)
      }
    } catch (error) {
      ElMessage.error(`${action}失败`)
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 删除品牌
const handleDelete = async (row) => {
  ElMessageBox.confirm(
    `确定要删除品牌 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      const res = await deleteBrandById(row.id)
      
      if (res && res.status === 200) {
        // 从所有数据中删除
        const index = allBrands.value.findIndex(brand => brand.id === row.id)
        if (index > -1) {
          allBrands.value.splice(index, 1)
        }
        // 重新获取分页数据
        getBrandList()
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getBrandList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getBrandList()
}

// 提交表单
const handleSubmit = () => {
  brandFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        let res
        
        if (dialogType.value === 'add') {
          // 新增品牌 - 适配后端字段格式
          const addData = {
            bname: brandForm.name,
            bsex: brandForm.sex,
            bremarks: brandForm.remarks,
            bstate: brandForm.status
          }
          console.log('新增品牌请求数据:', addData)
          res = await addBrand(addData)
          console.log('新增品牌响应:', res)
          
          // 检查后端返回的字符串响应
          if (res === '添加成功' || (res && res.status === 200)) {
            ElMessage.success('新增品牌成功')
            // 重新获取品牌列表
            console.log('新增成功，开始重新获取数据...')
            await FindAllBrands()
            console.log('数据重新获取完成')
          } else {
            ElMessage.error(res?.message || '新增品牌失败')
            return
          }
        } else {
          // 编辑品牌 - 适配后端字段格式
          const updateData = {
            bid: brandForm.id,
            bname: brandForm.name,
            bsex: brandForm.sex,
            bremarks: brandForm.remarks,
            bstate: brandForm.status
          }
          res = await updateBrand(updateData)
          console.log('编辑品牌响应:', res)
          
          // 检查后端返回的响应（可能是字符串或对象）
          if (res === '修改成功' || (res && res.status === 200)) {
            ElMessage.success('编辑品牌成功')
            // 重新获取品牌列表
            await FindAllBrands()
          } else {
            ElMessage.error(res?.message || '编辑品牌失败')
            return
          }
        }
        
        dialogVisible.value = false
        handleReset()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增品牌失败' : '编辑品牌失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  brandFormRef.value?.resetFields()
  Object.assign(brandForm, {
    id: '',
    name: '',
    sex: '通用',
    remarks: '',
    status: 1
  })
}


</script>

<style scoped>
.brand-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.brand-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>